package com.ikingtech.platform.business.message.service.router;

import com.ikingtech.framework.sdk.enums.message.MessageSendChannelEnum;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.push.common.*;
import lombok.RequiredArgsConstructor;

import java.util.Map;

import static com.ikingtech.framework.sdk.utils.Tools.Str.CONTENT_PLACEHOLDER_PREFIX;
import static com.ikingtech.framework.sdk.utils.Tools.Str.CONTENT_PLACEHOLDER_SUFFIX;

/**
 * @author tie yan
 */
@RequiredArgsConstructor
public class SmsMessageRouter implements MessageRouter{

    @Override
    public RouteResult route(RouteRequest request) {
        PushRequest pushRequest = this.parseBody(request.getChannelId(),
                request.getChannelTemplateId(),
                request.getTemplateContent(),
                request.getParamDefinitionMap(),
                request.getRedirectDefinitinoMap(),
                request.getMessageWrapper());
        DeliverResult result = PushManager.sms().send(pushRequest, request.getTarget().getPhone());
        return new RouteResult(pushRequest.getBody().getText(), Tools.Coll.convertList(pushRequest.getBody().getRedirectTo(), MessageRedirect::getRedirectLink), result.getSuccess(), result.getCause());
    }

    /**
     * 格式化消息内容
     *
     * @param content 消息内容模板
     * @param messageWrapper 消息参数
     * @return 格式化后的消息
     */
    private PushRequest parseBody(String smsId,
                                  String smsTemplateId,
                                  String content,
                                  Map<String, String> paramDefinitions,
                                  Map<String, String> redirects,
                                  Object messageWrapper) {
        PushRequest pushRequest = new PushRequest();
        MessageBody body = new MessageBody();
        pushRequest.setAppConfigId(smsId);
        Map<String, Object> messageParamMap = Tools.Json.objToMap(messageWrapper);
        if (Tools.Str.isNotBlank(smsTemplateId)) {
            pushRequest.setTemplateId(smsTemplateId);
            if (Tools.Coll.isNotBlankMap(messageParamMap)) {
                pushRequest.setTemplateParams(this.convertToTemplateParam(paramDefinitions, messageParamMap));
            }
        } else {
            if (Tools.Coll.isNotBlankMap(messageParamMap)) {
                body.setText(Tools.Str.replace(content, CONTENT_PLACEHOLDER_PREFIX, CONTENT_PLACEHOLDER_SUFFIX, messageParamMap));
            } else {
                body.setText(content);
            }
        }
        Boolean ignoreRedirect = (Boolean) messageParamMap.get("ignoreRedirect");
        if (!Boolean.TRUE.equals(ignoreRedirect)) {
            body.setRedirectTo(this.createMessageRedirect(redirects, messageParamMap));
        }
        pushRequest.setBody(body);
        return pushRequest;
    }

    @Override
    public MessageSendChannelEnum channel() {
        return MessageSendChannelEnum.SMS;
    }
}
